package com.wujunshen.algorithm.leetcode.depth.first.search;

import java.util.ArrayList;
import java.util.List;

/**
 * @author frank woo(吴峻申) <br>
 *     email:<a href="mailto:frank_wjs@hotmail.com">frank_wjs@hotmail.com</a> <br>
 * @date 2022/7/25 12:44<br>
 */
public class 路径总和II {
  public List<List<Integer>> pathSum(TreeNode1 root, int targetSum) {
    List<List<Integer>> result = new ArrayList<>();
    pathSum(root, targetSum, new ArrayList<>(), result);
    return result;
  }

  public void pathSum(TreeNode1 root, int sum, List<Integer> sol, List<List<Integer>> result) {
    if (root == null) {
      return;
    }
    sol.add(root.val);

    if (root.left == null && root.right == null && sum == root.val) {
      result.add(new ArrayList<>(sol));
    } else {
      pathSum(root.left, sum - root.val, sol, result);
      pathSum(root.right, sum - root.val, sol, result);
    }

    sol.remove(sol.size() - 1);
  }
}
